import React,{Component} from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from '@/common/layer';
import Rate from '@/Components/rate';
import DDView from '@/Components/ddview';
import InlinePicker from '@/Components/inlinepicker';

class Application extends Component{
    constructor(props){
        super(props);
        this.state={
            statusArr:[
                {
                    value:0,
                    label:'待处理'
                },
                {
                    value:2,
                    label:'进行中'
                },
                {
                    value:3,
                    label:'放款中'
                },
                {
                    value:4,
                    label:'成功'
                }
            ],
            activeStatus:0,
            page:1,
            canLoad:true,
            productList:[],

            // stop
            stopShow:false,
            stopOpen:false,
            stopReason:[
                {
                    value:0,
                    label:'资质不好'
                },
                {
                    value:1,
                    label:'真的资质不好'
                }
            ],
            activeStopReason:'',
            otherReasonText:'',
            activeId:null,

            //rate
            rateShow:false,
            rateOpen:false,
            activeManagerId:null,
            managerText:'',
            managerScore:1,

            activeProductId:null,
            productText:'',
            productScore:1


        }
        this.dict={
            loanAmount:['1万','2万','3万','4万','5万','10万','15万','20万','30万','50万','100万','200万','300万','500万']
        }
    }

    async getApply(){
        this.setState({
            canLoad:false
        })
        let res=await util.ajax({url:`/member/apply/list?status=${this.state.activeStatus}&page=${this.state.page}&limit=6`,type:"POST"})
        // if (!res) return
        this.setState({
            page:this.state.page+1,
            productList:[...this.state.productList,...res.data.data.rows]
        },()=>{
                this.setState({
                    canLoad:(this.state.productList>=res.data.data.total)?false:true
                })
        })
    }

    componentDidMount(){
       //  this.getApply();
    }

    // for stop
    stopModelOpen(){
        this.setState({
            stopShow:true
        })
        
    }

    stopModelClose(){
        this.setState({
            stopShow:false
        })
    }


    async stopSubmit(){
        let res=await util.ajax({url:`/member/apply/modifyCancel/${this.state.activeId}?reason=${this.state.activeStopReason}其他原因${this.state.otherReasonText}`})
        this.stopModelClose()
        this.setState({
            page:1,
            productList:[]
        },()=>{
            layer.open({
                content:"已中止",
                btn:"确定"
            })
            this.getApply()
        })
    }

    // for rate

    rateModelOpen(){
        this.setState({
            rateShow:true
        })
    }

    rateModelClose(){
        this.setState({
            rateShow:false
        })
    }

    async rateSubmit(){
        let res=await util.ajax({url:`/member/comment/manager/${this.state.activeManagerId}?content=${this.state.managerText}&score=${this.state.productScore}&applyId=${this.state.activeId}`,type:'POST'})
        let res2=await util.ajax({url:`/member/comment/product/${this.state.activeProductId}?content=${this.state.productText}&score=${this.state.productScore}&applyId=${this.state.activeId}`,type:'POST'})
        this.rateModelClose();
        this.setState({
            page:1,
            productList:[]
        },()=>{
            layer.open({
                content:"评价成功",
                btn:"确定"
            })
            this.getApply()
        })
    }

    // for render
    // 获得订单状态
    getStatusImg(received_status,status,canceled){
        if (canceled===1)
        {
            return <img src={`/assets/wechat/status5.png`} alt=""/>
        }

        if (typeof status === 'undefined')
        {
            return null
        }
        else
        {
            if (received_status > 1)
            {
                return <img src={`/assets/wechat/status0.png`} alt=""/>
            }else{
                return <img src={`/assets/wechat/status${status}.png`} alt=""/>
            }
        }
    }

    // 获得对应操作，详细见项目下 PAGE.md
    getControl(status,canceled,received_status,commented,id,productId,managerId){
        
        if (canceled === 1)
        {
            return <a href="javascript:;">已中止申请</a>
        }

        if (received_status > 1){
            return null
        }

        switch (status){
            case 0:
            case 3:
            case 5:
                return null
                break;
            case 1:
            case 2:
                return <a className="btn" href="javascript:;" onClick={()=>{this.setState({activeId:id});this.stopModelOpen();}}>中止申请</a>
                break;
            case 4:
                if (commented===0)
                {
                    
                    return <a className="btn" href="javascript:;" onClick={()=>{this.setState({activeId:id,activeManagerId:managerId,activeProductId:productId});this.rateModelOpen();}}>评价</a>
                }else{
                    return <a href="javascript:;">已评价</a>
                }
                break;
            default:
                return null
                break;
        }
    }

    componentDidMount(){
        if (!localStorage.token){
            layer.open({
                content:"您尚未登录，无法查看进度",
                btn:"去登录",
                yes:function(){
                    window.location.href=`./login.html?redirect_uri=${encodeURIComponent(window.location.pathname)}`
                }
            })
        }

        if (parseInt(localStorage.userType) !== 1){
            layer.open({
                content:"您还不是会员，请以会员身份查看进度",
                btn:"去登录",
                yes(){
                    window.location.href=`./login.html?redirect_uri=${encodeURIComponent(window.location.pathname)}`
                }
            })
        }
    }

    render(){

        let products=this.state.productList.map((item)=>{
            return(
                <li key={Math.random().toString(16).substring(2)}>
                    <div className="title">
                        <span>{item.instName}-{item.productName}</span>
                        <span className="qd">渠道商：{item.managerName}</span>
                    </div>
                    <div className="info">
                        <div className="k">
                            <p className="num">{this.dict.loanAmount[item.loanAmount]}</p>
                            <p className="txt">贷款金额</p>
                        </div>
                        <div className="k">
                            <p className="num">{(item.createTime)?item.createTime.split(' ')[0]:''}</p>
                            <p className="txt">申请时间</p>
                        </div>
                        <div className="k">
                            <p className="num">{(item.resultTime)?item.resultTime.split(' ')[0]:'无'}</p>
                            <p className="txt">放款时间</p>
                        </div>
                        <div className="k">
                            {this.getStatusImg(item.received_status,item.status,item.canceled)}
                            {this.getControl(item.status,item.canceled,item.received_status,item.commented,item.id,item.productId,item.managerId)}
                        </div>
                        <div className="cb"></div>
                    </div>
                </li>
            )
        })
        
        let stopModel=<div className="stopmodel" onClick={this.stopModelClose.bind(this)}>
            <div className="stop" onClick={(e)=>{e.stopPropagation()}}>
                <div className="title">中止原因</div>
                <InlinePicker groups={this.state.stopReason} onChange={(a,b)=>{this.setState({activeStopReason:b})}}/>
                <div className="title">其他</div>
                <textarea value={this.state.otherReasonText} onChange={(e)=>{this.setState({otherReasonText:e.target.value})}}></textarea>
                <a href="javascript:;" className="btn" style={{backgroundColor:'#009DE6'}} onClick={this.stopSubmit.bind(this)}>确认</a>
                <a href="javascript:;" className="btn" onClick={this.stopModelClose.bind(this)}>取消</a>
            </div>
        </div>

        let rateModel=<div className="ratemodel active" onClick={this.rateModelClose.bind(this)}>
            <div className="rate" onClick={(e)=>{e.stopPropagation()}}>
                <div className="title">评价您的渠道商</div>
                <textarea value={this.state.managerText} onChange={(e)=>{this.setState({managerText:e.target.value})}}></textarea>
                <span style={{verticalAlign:'super'}}>评分：</span><Rate value={this.state.managerScore} onChange={(val)=>{this.setState({managerScore:val})}}/>
                <div className="title">评价您的产品</div>
                <textarea value={this.state.productText} onChange={(e)=>{this.setState({productText:e.target.value})}}></textarea>
                <span style={{verticalAlign:'super'}}>评分：</span><Rate value={this.state.productScore} onChange={(val)=>{this.setState({productScore:val})}}/>
                <a href="javascript:;" className="btn" style={{backgroundColor:'#009DE6'}} onClick={this.rateSubmit.bind(this)}>确认</a>
                <a href="javascript:;" className="btn" onClick={this.rateModelClose.bind(this)}>取消</a>
            </div>
        </div>

        let userinfo=<div className="userinfo">
            <div style={{height:"20px"}}></div>
            <img src={localStorage.avatar || '/assets/wechat/default-avatar.png'} alt=""/>
            <p>{localStorage.name}</p>
            <p style={{fontSize:"16px"}}>{localStorage.telPhone}</p>
        </div>

        return (
            <div className="application">
                <DDView className="apppanel" action={this.getApply.bind(this)} canAction={this.state.canLoad}>
                    <InlinePicker className="tab" value={this.state.activeStatus} groups={this.state.statusArr} onChange={(val)=>{this.setState({activeStatus:val,productList:[],page:1},()=>{this.getApply();}); }}/>

                    <ul className="productlist">
                        {products}
                    </ul>
                    
                </DDView>
                {(this.state.stopShow)?stopModel:null}
                {(this.state.rateShow)?rateModel:null}
            </div>
            
        )
    }
}

ReactDom.render(<Application />,document.getElementById("app"));